package com.cxlin.cwanandroid.ui.project.viewmodel

import androidx.lifecycle.viewModelScope
import com.cxlin.base.BaseViewModel
import com.cxlin.base.model.api.Result
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import com.cxlin.cwanandroid.model.bean.SystemParent
import com.cxlin.cwanandroid.model.repository.ProjectRepository
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/5/14 13:55
 */
class ProjectTabViewModel(private val repository: ProjectRepository) : BaseViewModel() {


    sealed class ProjectTabUiState : UiState {
        object Idel : ProjectTabUiState()
        data class ProjectTypes(val result: List<SystemParent>) : ProjectTabUiState()
    }

    sealed class ProjectTabEvent : UiEvent {
        class ToastEvent(val message: String, val short: Boolean = false) : ProjectTabEvent()
    }

    sealed class ProjectTabUiIntent : UiIntent {
        class GetProjectType() : ProjectTabUiIntent()
    }

    override fun handleIntent(intent: UiIntent) {
        when (intent) {
            is ProjectTabUiIntent.GetProjectType -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        val result = repository.getProjectType()
                        if (result is Result.Success) {
                            mUiStateFlow.update {
                                ProjectTabUiState.ProjectTypes(result.data)
                            }
                        } else if (result is Result.Error) {
                            mEffectFlow.emit(LoginViewModel.LoginEvent.ToastEvent(result.exception.message ?: "网络异常", true))
                        }
                    }
                }
            }
        }

    }

    override fun createInitState(): UiState {
        return ProjectTabUiState.Idel
    }
}